Central Article

Creating a Two-Way Video Chat Application in Macromedia Central


Table of Contents

  1. Introduction
  2. The vChat Application
  3. The Client Side: Building the Application
  4. The Client Side: Building the Pod
  5. Lessons Learned

The Client Side: Building the Pod

The interesting client-side code is in the Central pod that comes with the application.

In Flash MX or Flash MX 2004, create a new pod.fla file and make its Stage size 160 x 160 pixels. Create a Timeline like the one in Figure 2.

The Timeline for the vChat Pod

Figure 2. The Timeline for the vChat Pod

Let's start building the application, one screen at the time. In the login layer, add two Text Input Field components from the Central Components panel and call them room_txt and name_txt. In the label property, type Room and Login and set the Is Required flag to true on both. Now add a Push Button component (always from the Central Components panel, of course) and call it login_pb. Give it the label Login and the Click Handler doLogin.

Hide and lock the login layer and move to the list layer. Add a Push Button component to the top left of the Stage, call it vChat_pb, give it the label vChat and the doVChat Click Handler. Now add a List Box component and call it users_lb. Give it the Change Handler onListClick.

That's all you need for the list layer so hide it, lock it, and move to the video layer. Create a new video from the Library menu and drag two instances of it to the Stage. Make one of them big and the other one small, placed on top of the first. Call the big video videoIn and the small video videoOut. Draw a black rectangle around the videoOut video box and add another Push Button component to the Stage. Call it done_pb and give it the Done label and the Click Handler doDone.

Now, in the actions layer, either do #include "pod.as" or type in the code that appears in the snippets from here to the end of this section. Because there's a lot of code in this pod, I'll go through it one function at the time.

First you define an onActivate method:

//Central calls this when the pod is opened
function onActivate(dock, podid, viewerId, position, baseTabIndex, data)
{
   showScreen("login");

   //Global variables
   gServerName = "yourserver.com";
   gAppName = "central_vchat";

   this.gConsole = dock;

   //Local table of the users I know
   this.usersIKnow = new Object();

   //Get the local Shared Object (we save the last room and username used in it)
   this.localSO = SharedObject.getLocal("vChat");
   if (this.localSO.data.room == undefined) {
      this.localSO.data.room = "fun";
      this.localSO.data.userName = "";
   }
   //Populate UI
   this.room_txt.setValue(this.localSO.data.room);
   this.name_txt.setValue(this.localSO.data.userName);
}

This is the first method that Central calls on this pod. You define some global variables, save a reference to the console (you'll need it to pop up notifications), create a usersIKnow table (you'll use it later), and get a local shared object, in which you save the last room and username that the user selects. You then populate the login screen UI with the values retrieved from the local shared object.

Next you define an onDeactivate method:
//Central calls this when the pod is closed
function onDeactivate()
{
   //Close everything
   videoOut.clear();
   nsOut.close();
   videoIn.clear();
   nsIn.close();
   attachAudio(null);
   connectToFlashCom(false); //Disconnect
   showScreen("login");
}

Whenever a user closes the pod, the onDeactivate method is called by Central. In it, you close all streams (in case you were in the middle of a vChat) and disconnect from Flash Communication Server. This triggers an onDisconnect on the server side (see the code above), which cleans up the user's shared object.

Next you define all the necessary UI handlers, starting with doLogin:


//login_pb Click Handler
function doLogin() {
   if (this.login_pb.getLabel() == "Login") {
      //Save room and login in localSO
      this.localSO.data.room = this.room_txt.getValue();
      this.localSO.data.userName = name_txt.getValue();

      //If successful, it will showScreen("list") and populate it
      connectToFlashCom(true);
   } else
      connectToFlashCom(false); //Disconnect
}

Whenever a user clicks Login, you save the room and username in the local shared object (for next time) and connect to Flash Communication Server. If the button label says Logout, you disconnect from the server instead.

The two button handlers below are invoked whenever the user clicks the vChat button to initiate a vChat or clicks the Done button to finish it. The doVChat function sets a flag so you won't pop up a notification when onSync comes around (you'll see what I mean in a minute). Then you set the talkingTo member of your own slot and of the person you want to talk to (the one that's selected in the users_lb list box). This triggers an onSync on all clients, including yourself:

//vChat_pb Click Handler
function doVChat() {
   this.initiator = true; //Don't trigger an alert, I initiated this vChat

   //This will trigger an onSync/onSlotChanged on all clients
   this.so.data[this.users_lb.getSelectedItem().data].talkingTo = this.myID; //They're talking to me 
   this.so.data[this.myID].talkingTo = this.users_lb.getSelectedItem().data; //I'm talking to them 
}

//done_pb Click Handler
function doDone() {
   //This will trigger an onSync/onSlotChanged on all clients
   this.so.data[this.so.data[this.myID].talkingTo].talkingTo = null;
   this.so.data[this.myID].talkingTo = null;
}

The two methods below are pretty self-explanatory. The onListClick handler disables the vChat button if you selected yourself or someone who's already talking with someone else. The showScreen method is how you go from one screen to the other; it just sets the _visible property of each element on the Stage:

//users_lb Change Handler
function onListClick() {
   //You can't initiate a vChat with yourself or with
   //someone who's already chatting with someone else.
   var selID = this.users_lb.getSelectedItem().data;
   this.vChat_pb.setEnabled((selID != this.myID) && (this.so.data[selID].talkingTo == null));
}

//Changes the UI: name can be ["login" | "vchat" | "list"]
function showScreen(name) {
   this.name_txt._visible = (name == "login");
   this.room_txt._visible = (name == "login");

   this.login_pb.setLabel((name == "login") ? "Login" : "Logout");
   this.login_pb._y = (name == "login") ? 100 : 0;
   this.login_pb._visible = (name != "vchat");

   this.users_lb._visible = (name == "list");
   this.vChat_pb._visible = (name == "list");

   this.videoIn._visible = (name == "vchat");
   this.videoOut._visible = (name == "vchat");
   this.done_pb._visible = (name == "vchat");
   this.square_mc._visible = (name == "vchat");
}

The code below executes as soon as the pod loads (even before onActivate). All you do is define NetConnection and attach two methods to it. As you saw in the section on the server-side code, as soon as a connection to a client is accepted you call setID on the client to tell it what ID the server assigns to it. The client shouldn't be doing anything before this call arrives, so in onStatus don't check for NetConnection.Connect.Success. Instead, check for the opposite: If something goes wrong (the connection is closed or rejected or fails) then you just show the login screen again. The setID method is called right after a successful connection is established. After you save your unique ID in the myID variable, you show the user list screen and connect the shared object to populate the list:

//Create a NetConnection
nc = new NetConnection();
nc.mc = this;
nc.onStatus = function(info) {
   if (info.code != "NetConnection.Connect.Success")
      showScreen("login"); //Back to login screen if the connection is closed/rejected/failed.
}
nc.setID = function(id) { //Called by the server
   this.mc.myID = id;
   showScreen("list");
   connectSO();
}

The connectSO function below connects this client to the user's remote shared object and defines an onSync to it. (This is a small variation of my favourite onSync, which I use all the time. For more information about it, see my blog entry about it.) The onSync calls updateList (which just populates the user list) on the first onSync invocation, and then onSlotChanged (whenever a new user is created or a user starts or stops a vChat), or onSlotDeleted (whenever a user disconnects):

//Called by the nc.setID
function connectSO() {
   //Get the users Shared Object and attach my favourite onSync to it.
   this.so = SharedObject.getRemote("users", nc.uri, false);
   this.so.mc = this;
   this.so.firstTime = true;
   this.so.onSync = function(list) {
      if (this.firstTime) {
         this.firstTime = false;
         this.mc.updateList(); //Only update the list, skip the notification
         return;
      }
      for (var k in list) {
         if ((list[k].code == "change") || (list[k].code == "success"))
            this.mc.onSlotChanged(list[k].name); //This will pop-up a notification
         else if (list[k].code == "delete")
            this.mc.onSlotDeleted(list[k].name); //This will pop-up a notification
      }
   }
   this.so.connect(nc); //This will trigger an onSync
}

The onSlotChanged function is the hardest function you'll write, so look at it carefully:

//Called by onSync whenever a new user is created or a user starts or stops a vChat
this.onSlotChanged = function(id) {
   if (!this.usersIKnow[id]) { //User is new to me

      if (id != this.myID) { //Don't display a "user is connected" notice for myself.
         var notice = new Object();
         notice.name = this.so.data[id].name +" is connected";
         notice.description = this.so.data[id].name+" connected to "+this.localSO.data.userName;
         notice.timeout = 5;
         notice.alert = true;
         notice.engageString = "";
         this.gConsole.addNotice(notice);
      }

      //Save the name in the local table.
      this.usersIKnow[id] = this.so.data[id].name;
   }

   if (id == this.myID) { //It's myself

      if (this.so.data[this.myID].talkingTo != null) {
         //This means I either started a vChat or someone else wants to chat with me.
         showScreen("vchat");

         if (this.initiator)
            this.initiator = false;
         else {
            //Someone else initiated this vChat. Get my attention.
            var notice = new Object();
            notice.name = this.so.data[this.so.data[this.myID].talkingTo].name +" started a vChat with you";
            notice.description = this.so.data[this.so.data[this.myID].talkingTo].name +" started a vChat with you";
            notice.timeout = 10;
            notice.alert = true;
            notice.engageString = "";
            this.gConsole.addNotice(notice);
         }

         //Start receiving their stream
         nsIn = new NetStream(nc);
         videoIn.attachVideo(nsIn);
         attachAudio(nsIn);
         nsIn.play("user"+this.so.data[this.myID].talkingTo);

         //Start publishing my stream
         myCam = Camera.get();
         myCam.setMode(240,240,15);
         myCam.setKeyFrameInterval(30);
         myMic = Microphone.get();
         myMic.setRate(22);
         videoOut.attachVideo(Camera.get());
         nsOut = new NetStream(nc);
         nsOut.attachVideo(Camera.get());
         nsOut.attachAudio(Microphone.get());
         nsOut.publish("user"+this.myID);
      } else {
         //Either of us clicked on "Done"
         videoOut.clear();
         nsOut.close();
         videoIn.clear();
         nsIn.close();
         attachAudio(null);

         showScreen("list");
      }
   }

   //Update the list
   this.updateList();
}

Here's what it all means. First you check whether or not the slot is new to this client. The code does this by checking the local usersIKnow table. If it's a new user, and it's not yourself, you add a "UserX is connected" notice, which automatically disappears in five seconds—just as any IM client does. Then you save the username in the usersIKnow table so that the next time there's a change to that user's slot, you don't display another "UserX is connected" alert.

Moving on. If the slot that's changed is yourself, it could mean one of four things:

  1. You started a vChat with someone
  2. Someone else started a vChat with you
  3. You just connected
  4. Your vChat is over (either you or the other person clicked Done)

If the talkingTo member of your slot is not null, it's either case 1 or 2. If the initiator flag is set, you're in case 1 and you don't put up a notice. Otherwise, it's case 2 so this pod needs to attract your attention. This happens by popping up a Central notification for 10 seconds.

After that, you go to the vChat screen and publish a video and audio stream (with the name "user"+this.myID). You also play the stream of the other person you're "vChatting" with. Using the ID as part of the stream name makes it all easy!

If the talkingTo member is null, then it's case 3 or 4. Either way, you stop the streaming. (If it's case 3, nothing was streaming, but closing a closed stream doesn't hurt anything.) And then you go back to the list screen (you might be on it already).

Finally, you update the user list (remember that every client does this because every client gets an onSync):

//Called by the onSync whenever a user leaves
this.onSlotDeleted = function(id) {

   //Add a notice (note how we get the data from the
   //local usersIKnow table, used as a cache. We can't use
   //the Shared Object slot contents because it's too late!)
   var notice = new Object();
   notice.name = this.usersIKnow[id] +" left";
   notice.description = this.usersIKnow[id] +" left";
   notice.timeout = 5;
   notice.alert = true;
   notice.engageString = "";
   this.gConsole.addNotice(notice);

   //Delete from local table
   delete this.usersIKnow[id];

   //Update the list
   this.updateList();
}

The onSlotDeleted function gets called whenever someone else disconnects from the application—because they close the pod, close Central, unplug their network cable, or whatnot. In this case you add a regular IM-style notification, saying that the user left. Notice that to display the name of the user who just left you have to get it from the usersIKnow table. Looking at the slot in the shared object returns null because the slot has already been deleted on the server side! After displaying the notification you delete the slot from the local usersIKnow cache and repopulate the user list:

//Updates the user list
this.updateList = function() {
   //This implementation is not scalable, but it will do for this tutorial
   this.users_lb.removeAll();
   for (var i in this.so.data) {
      if (this.so.data[i].talkingTo != null) //They're in the middle of a vChat
         this.users_lb.addItem(this.so.data[i].name+" (talking to "+this.so.data[this.so.data[i].talkingTo].name+")", i);
      else
         this.users_lb.addItem(this.so.data[i].name, i);
   }
}

The above function is called by onSync, onSlotChanged, and onSlotDeleted. It populates the users_lb list box with the names of the users connected to the application and it appends "(talking to xxx)" for those users who are in the middle of a vChat. It also adds their ID as a data field (so that the doVChat and the onListClick handlers can do their job well).

Hang tight, we're almost there. All you have to do now is define the connectToFlashCom function, which either connects you to the Flash Communication Server or disconnects you from it:

//Utility method: strips a char from a string.
function removeChar(char,str) {
   var newStr = "";
   while (str.indexOf(char) != -1) {
      newStr = str.substring(0, str.indexOf(char)) + str.substring(str.indexOf(char)+1);
      str = newStr;
   }
   return str;
}

//Connects or disconnects to the Flash Communication Server
function connectToFlashCom(bool) {
   if (bool) {
      var roomName = this.localSO.data.room.toLowerCase(); //Cleans up the room name
      roomName = removeChar(" ",roomName);
      roomName = removeChar("/",roomName);
      nc.connect("rtmp://"+gServerName+"/"+gAppName+"/"+roomName, this.localSO.data.userName);
   } else
      nc.close();
}

	

First you define a little removeChar utility method to strip out illegal application instance characters from whatever the user typed in the room text field. The connectToFlashCom function cleans up the room_txt text field (its value was saved in the local shared object during the doLogin function) and uses it as an application instance name. This allows you to have multiple rooms on the same server. You also pass the username to the connect call so that the server side can create a slot for you in the user's shared object. If the bool parameter is false, you just close the connection. This triggers an onStatus with info.code == "NetConnection.Connect.Closed", which takes the UI back to the login screen.

One more line you can't forget!

//Tell Central we're a Pod. This will trigger onActivate
Central.initPod( this, this );

This tells Central that you're a pod and you're alive and kicking. Central responds by calling onActivate on you (which you defined first).

That's all there is to it! It wasn't too much, was it?

Save your file, package it in a product (look at the Central SDK documentation on how to do this), and start vChatting with your friends!